import store from '@/store';
import util from '@/libs/util';
// import nedb from '@/db/nedb'
// import router from '@/router'
import { sendSock } from '../websocket';
// import { ipcRenderer } from 'electron'

/**
 * 登陆成功
 */
function deviceAuthRspHandle (msg) {
    // let user = JSON.parse(msg.message).Extra;

    // 登陆成功后 立马发送一次心跳
    // let heartBeatMsg = {
    //     Id: 1001,
    //     MsgType: 'HeartBeatReq',
    //     AccessToken: JSON.parse(msg.message).AccessToken
    // };
    let heartBeatMsg = {
        Id: 1001,
        MsgType: 'HeartBeatReq',
        AccessToken: ''
    };
    sendSock(heartBeatMsg);

    // 登陆成功后 打开重连功能
    store.dispatch('websocket/account/SetRelogin', 'true');
    store.dispatch('websocket/account/SetUser', {}); // 设置用户信息
    // store.dispatch(
    //     'websocket/account/SetToken',
    //     JSON.parse(msg.message).AccessToken
    // ); // 设置token信息
    store.dispatch(
        'websocket/account/SetToken', ''
    ); // 设置token信息
    store.dispatch('websocket/account/SetLogin', true); // 修改登录状态
    // let wsInfo = {
    //     SetUser: user,
    //     SetToken: JSON.parse(msg.message).AccessToken
    // };
    let wsInfo = {
        SetUser: {},
        SetToken: ''
    };
    localStorage.setItem('wsInfo', JSON.stringify(wsInfo));
    // let params = {
    //     Id: 3050,
    //     MsgType: 'GetWeChatsReq',
    //     Content: { AccountType: user.AccountType, UnionId: user.UnionId }
    // }
    // sendSock(params);
    // store.dispatch("websocket/account/getWechats", user);
}

/**
 * 微信列表
 */
// function getWeChatsRspHandle(msg) {
//     let message = JSON.parse(msg.message);
//     console.log(message)
//     let wechats = message.WeChats ? message.WeChats : [];
//     if (wechats.length === 0) {
//         console.log("没有绑定微信");
//     } else {
//         // 根据是否绑定微信进行登录
//         let wechatsInfo = [];
//         let filterWechats = wechats.filter((w) => {
//             return w.IsOnline;
//         });
//         store.dispatch("websocket/account/SetWechats", filterWechats);
//         filterWechats.forEach((item) => {
//             wechatsInfo.push({
//                 WeChatId: item.WeChatId,
//                 IsLogin: true,
//             });
//         });
//         localStorage.setItem("wechatsInfo", JSON.stringify(wechatsInfo));
//         store.dispatch("websocket/account/wechatesLogin", wechatsInfo);
//     }
// }
function getWeChatsRspHandle (msg) {
    let message = JSON.parse(msg.message);
    let wechats = message.WeChats ? message.WeChats : [];
    if (wechats.length === 0) {
        console.log('没有绑定微信');
    } else {
        // 根据是否绑定微信进行登录
        let wechatsInfo = [];
        let filterWechats = wechats.filter((w) => {
            return w.IsLogined;
        });
        store.dispatch('websocket/account/SetWechats', filterWechats);
        filterWechats.forEach((item) => {
            wechatsInfo.push({
                WeChatId: item.WeChatId,
                IsLogin: true
            });
        });
        localStorage.setItem('wechatsInfo', JSON.stringify(wechatsInfo));
        store.dispatch('websocket/account/wechatesLogin', wechatsInfo);
    }
}

// /**
//  * 已登陆的微信处理
//  * @param {string} msg
//  */
// function weChatLoginNoticeRespHandle (msg) {
//   let message = JSON.parse(msg.message)
//   let wechatsLogin = JSON.stringify(message) !== '{}' ? message.WeChats : []
//   store.dispatch('SetWechatsLogin', wechatsLogin)
//   store.dispatch('SetDialog', 'PreviewPage')
// }

/**
 * 好友列表
 */
function friendPushNoticeHandle (msg) {
    let message = JSON.parse(msg.message);
    let count = message.Count || 0; // 好友数量
    let page = message.Page || 0;
    if (count === 0) return;
    // 如果有好友
    let userId = store.getters.userId;
    let wechatId = message.WeChatId;
    let friends = [];
    for (const friend of message.Friends) {
        friend.Page = page;
        friend.WeChatId = wechatId;
        friend.user = userId;
        friends.push(friend);
    }
    // console.log(friends)
    //   nedb.friends.insert(friends, (err, docs) => {
    //     // console.log(err || docs)
    //     if (err) return
    //     store.dispatch('conversation/SetCurrentFriends')
    //     // 判断是否推送完成
    //     nedb.friends.count(
    //       { user: userId, WeChatId: wechatId },
    //       (err, friendsCount) => {
    //         if (!err && friendsCount === count) {
    //           store.dispatch('SetFriends')
    //           if (store.getters.dialog === 'PreviewPage') {
    //             console.log('当前是PriviewPage')
    //           } else {
    //             store.dispatch('SetDialog', '')
    //           }
    //         }
    //       }
    //     )
    //   })
}

/**
 * 标签列表
 */
function contactLabelInfoNoticeHandle (msg) {
    let message = JSON.parse(msg.message);
    console.log('标签列表：ContactLabelInfoNotice');
    console.log(message);
    if (message.Labels && message.Labels.length > 0) {
        let doc = {};
        doc.WeChatId = message.WeChatId;
        doc.user = store.getters.userId;
        doc.Labels = message.Labels;

        // nedb.labels.update(
        //   { user: store.getters.userId, WeChatId: message.WeChatId },
        //   doc,
        //   { upsert: true },
        //   (err, numReplaced) => {
        //     console.log(err || numReplaced)
        //     store.dispatch('SetLabels')
        //   }
        // )
    }
}

// ==============================================================================
// =================================河蟹的分割线==================================
// ==============================================================================

/**
 * 微信下线
 */
function weChatOfflineNoticeHandle (msg) {
    console.log('微信下线通知：WeChatOfflineNotice');
    let mj = JSON.parse(msg.message);
    console.log(mj);
    let accountType = store.getters.user.AccountType;
    let unionId = Number(store.getters.user.UnionId);
    let sendMsg = {
        MsgType: 'GetWeChatsReq',
        Content: { AccountType: accountType, UnionId: unionId }
    };
    sendSock(sendMsg);
}

/**
 * 微信上线
 */
function weChatOnlineNoticeHandle (msg) {
    console.log('微信上线通知:WeChatOnlineNotice');
    let mj = JSON.parse(msg.message);
    console.log(mj);
    let accountType = store.getters.user.AccountType;
    let unionId = Number(store.getters.user.UnionId);
    let sendMsg = {
        MsgType: 'GetWeChatsReq',
        Content: { AccountType: accountType, UnionId: unionId }
    };
    sendSock(sendMsg);
}

export default {
    deviceAuthRspHandle,
    getWeChatsRspHandle,
    //   weChatLoginNoticeRespHandle,
    friendPushNoticeHandle,
    contactLabelInfoNoticeHandle,
    weChatOfflineNoticeHandle,
    weChatOnlineNoticeHandle
};
